<template>
    <div class="app-container page-wood-sales-note">
        <el-row :gutter="10" class="sumbit-btn-group mb8">
            <el-col class="flex-center" :span="1.5">
                <SearchInput
                    v-model="form.salesId"
                    :api="$Api.sales.order.list"
                    :params="{ pageNum: 1, pageSize: 10, auditStatus: 1 }"
                    searchKey="pactNum"
                    selectLabel="salesId"
                    placeholder="输入或查询合同号"
                    @change="searchInputChange"
                    :disabled="disabled"
                    :all="false"
                />
            </el-col>
            <div class="empty"></div>
            <template v-if="!deliveryId">
                <el-col :span="1.5">
                    <el-button
                        type="primary"
                        plain
                        icon="el-icon-plus"
                        size="mini"
                        @click="saveHandleAdd"
                        v-hasPermi="['business:salesDelivery:add']"
                        >保存并新增</el-button
                    >
                </el-col>
                <el-col :span="1.5">
                    <el-button
                        type="success"
                        plain
                        icon="el-icon-edit"
                        size="mini"
                        @click="submitForm"
                        v-hasPermi="['business:salesDelivery:add']"
                        >保存</el-button
                    >
                </el-col>
            </template>
            <template v-else>
                <el-col :span="1.5">
                    <el-button
                        type="primary"
                        plain
                        icon="el-icon-plus"
                        size="mini"
                        @click="newAddSell"
                        v-hasPermi="['business:salesDelivery:add']"
                        >新增</el-button
                    >
                </el-col>
                <template>
                    <el-col :span="1.5">
                        <el-button
                            type="success"
                            icon="el-icon-edit"
                            size="mini"
                            @click="setAuditStatus"
                            v-hasPermi="['business:salesDelivery:edit']"
                            >{{
                                form.auditStatus == 0 ? "审核" : "反审核"
                            }}</el-button
                        >
                    </el-col>
                </template>
                <template v-if="form.auditStatus != 1">
                <el-col :span="1.5">
                    <el-button
                        type="success"
                        plain
                        icon="el-icon-edit"
                        size="mini"
                        @click="submitForm"
                        v-hasPermi="['business:salesDelivery:add']"
                        >保存</el-button
                    >
                </el-col>
            </template>
            </template>
            <template v-if="false">
                <el-col :span="1.5">
                    <el-button
                        type="primary"
                        plain
                        icon="el-icon-plus"
                        size="mini"
                        @click="purchasingSystem"
                        >收款</el-button
                    >
                </el-col>
            </template>
        </el-row>

        <div class="table-area">
            <el-form
                :model="form"
                ref="form"
                :inline="true"
                v-show="showSearch"
                :rules="rules"
                label-width="90px"
            >
                <el-form-item label="客户" prop="customerName">
                    <SupplierSelect
                        :typeSelect = customer
                        v-model="form.customerName"
                        placeholder="请输入客户"
                        :disabled="disabled"
                    />
                </el-form-item>

                <el-form-item label="单据日期" prop="billTime">
                    <el-date-picker
                        clearable
                        size="small"
                        v-model="form.billTime"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="选择单据日期"
                        :disabled="disabled"
                    >
                    </el-date-picker>
                </el-form-item>

                <el-form-item label="单据编号" prop="deliveryId">
                    <el-input
                        v-model="form.deliveryId"
                        placeholder="请输入单据编号"
                        :disabled="true"
                        size="small"
                    />
                </el-form-item>

                <el-form-item label="销售员" prop="salesName">
                    <SupplierSelect
                        :typeSelect = sales
                        v-model="form.salesName"
                        placeholder="请输入销售员"
                        :disabled="disabled"
                    />
                </el-form-item>

                <el-form-item label="税率(%)" prop="taxRate">
                    <el-input-number
                        v-model="form.taxRate"
                        controls-position="right"
                        :min="0"
                        :max="100"
                    ></el-input-number>
                </el-form-item>

                <el-form-item label="车号" prop="carNo">
                    <el-input
                        v-model="form.carNo"
                        placeholder="请输入车号"
                        clearable
                        size="small"
                        @keyup.enter.native="handleQuery"
                    />
                </el-form-item>
                <JustTimeInventory @selectItemsClick="selectItemsClick" />
                <!-- 表格开始 -->
                <TableForm
                    ref="TableForm"
                    :list="form.woodSalesDeliveryGoodsList"
                    :column="getSalesTableData"
                    :summary="true"
                    :loading="loading"
                    :disabled="disabled"
                >
                    <el-table-column width="100" label="操作" fixed="right">
                        <template slot-scope="scope">
                            <div class="btn-group">
                                <div class="btn-add">
                                    <el-button
                                        type="primary"
                                        icon="el-icon-edit"
                                        size="mini"
                                        circle
                                        @click="handleUpdate(scope.row)"
                                    />
                                </div>
                            </div>
                        </template>
                    </el-table-column>
                </TableForm>
                <!-- 表格结束 -->

                <!-- 备注信息 -->
                <el-form-item class="form-remark" prop="remark">
                    <el-input
                        type="textarea"
                        placeholder="请输入备注信息"
                        v-model="form.remark"
                        clearable
                        size="small"
                        rows="5"
                    />
                </el-form-item>
                <img
                    v-if="form.auditStatus == 1"
                    :src="img.audit"
                    class="img-audit"
                />
            </el-form>
        </div>

        <!-- 添加或修改销售出库信息对话框 -->
        <el-dialog
            :title="title"
            :visible.sync="open"
            width="500px"
            append-to-body
            :close-on-click-modal="false"
        >
            <el-form
                ref="form"
                :model="formData"
                :rules="rules"
                label-width="80px"
                class="data-edit-form"
            >
                <el-form-item label="厚度" prop="ply">
                    <el-input v-model="formData.ply" placeholder="请输入厚度" />
                </el-form-item>
                <el-form-item label="宽度" prop="width">
                    <el-input
                        v-model="formData.width"
                        placeholder="请输入宽度"
                    />
                </el-form-item>
                <el-form-item label="长度" prop="length">
                    <el-input
                        v-model="formData.length"
                        placeholder="请输入长度"
                    />
                </el-form-item>
                <el-form-item label="片数" prop="sliceCount">
                    <el-input
                        v-model="formData.sliceCount"
                        placeholder="请输入片数"
                    />
                </el-form-item>
                <el-form-item label="单包方数" prop="oneCount">
                    <el-input
                        v-model="formData.oneCount"
                        placeholder="请输入单包方数"
                    />
                </el-form-item>
                <el-form-item label="方数" prop="inCount">
                    <el-input
                        v-model="formData.inCount"
                        placeholder="请输入方数"
                        :disabled="true"
                    />
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="cancel">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>

import JustTimeInventory from "@/components/JustTimeInventory";
import CellInput from "@/components/CellInput";
import SearchInput from "@/components/SearchInput";
import SupplierSelect from "@/components/SupplierSelect";
import TableForm from "@/components/TableForm/preset";

export default {
    name: "salesDelivery",
    components: {
        JustTimeInventory,
        CellInput,
        SearchInput,
        SupplierSelect,
        TableForm,
    },
    data() {
        return {
            // 遮罩层
            loading: false,
            // 弹出层标题
            title: "",
            // 是否显示弹出层
            open: false,
            showSearch: true,
            // 商品实时库存查询参数
            queryParams: {
                pageSize: 10,
                pageNum: 1,
                baleNum: null,
            },
            // 表单参数
            formData: {
                ply: 0, // 厚度
                width: 0, // 宽度
                length: 0, // 长度
                sliceCount: 0, // 片数
                pieceCount: 0, // 件数
                inCount: 0, // 方数
                oneCount: 0, //单包方数
            },
            form: {
                deliveryId: "",
                salesId: "",
                isStatus: "0",
                auditStatus: 0,
                taxRate: 0,
                // 销售出库信息表格数据
                woodSalesDeliveryGoodsList: [
                    {
                        baleNum: "", // 包号
                        goodsName: "", // 品名
                        brandName: "", // 品牌
                        level: "", //等级
                        warehouse: "", // 仓库
                        ply: 0, // 厚度
                        width: 0, // 宽度
                        length: 0, // 长度
                        sliceCount: 0, // 片数
                        pieceCount: 0, // 件数
                        inCount: 0, // 方数
                        oneCount: 0, //单包方数
                        includedTaxPrice: 0, //含税单价
                        price: 0, // 单价
                        money: 0, // 金额
                        goodsStatus: "", // 货物状态
                        pactName: "", //开证公司
                        remark: "", // 备注
                        taxRate: "",
                        gcountId: "",
                    },
                ],
            },
            getSalesTableData: [
                { label: "包号", changeBlur: this.searchBaleNum},
                { label: "品名"},
                { label: "品牌"},
                { label: "等级"},
                { label: "仓库"},
                { label: "厚度(mm)"},
                { label: "宽度(mm)"},
                { label: "长度(m)" },
                { label: "片数"},
                { label: "件数", afterChange: this.moneyCount},
                { label: "单包方数", afterChange: this.moneyCount},
                { label: "方数", inputType: "none"},
                {
                    label: "含税单价", 
                    value: 'includedTaxPrice',
                    onchange: this.moneyCount,
                },
                { label: "金额"},
                { label: "货物状态"},
                { label: "开证公司", inputType: "none",value:'pactName'},
                { label: "备注(批量)"},
            ],
            // 表单校验
            rules: {
                customerName: [
                    {
                        required: true,
                        message: "客户不能为空",
                        trigger: "blur",
                    },
                ],
                billTime: [
                    {
                        required: true,
                        message: "单据日期不能为空",
                        trigger: "blur",
                    },
                ],
                orderId: [
                    {
                        required: true,
                        message: "订单号不能为空",
                        trigger: "blur",
                    },
                ],
                salesName: [
                    {
                        required: true,
                        message: "销售员不能为空",
                        trigger: "blur",
                    },
                ],
                carNo: [
                    {
                        required: true,
                        message: "车号不能为空",
                        trigger: "blur",
                    },
                ],
            },
            // 业务员
            salesman: null,
            //订单号
            deliveryId: "",
            mouseShow: false,
            price: null,
            // 组件替换条件
            customer:'customerName',
            sales: 'nickName',
            img: {
                audit: require("@/assets/images/bg@audit.png"),
            },
        };
    },
    created() {
        let { id } = this.$route.params;
        let { salesId } = this.$route.query;
        if (salesId) {
            this.form.salesId = salesId;
            this.getSalesOrderDetailList(salesId);
        } else if (id) {
            this.deliveryId = id;
            id && this.getSalesDelivery();
        }

        this.getReceiptCode();
    },
    computed: {
        disabled() {
            if (this.form.auditStatus == 1) {
                return !!this.orderId;
            }
        },
    },
    methods: {
        // 获取单据编号
        getReceiptCode(){
            let { id } = this.$route.params;
            if(id){
                this.form.deliveryId = id;
                return false;
            }
            this.$Api.onlyId.getId().then((res) => {
                let { data } = res;
                this.form.deliveryId = data;
            });
        },
        //  包 数据选择   单包方数计算: 方数 / 件数
        selectItemsClick(newData) {
            newData.forEach( (v) =>{
                v.oneCount = Number(v.inCount) / Number(v.pieceCount)
            })
            this.form.woodSalesDeliveryGoodsList = newData;
        },

        // 金额计算 ： 单价 * 方数
        moneyCount(d) {
            let { inCount, includedTaxPrice, money } = d;
            let t = ((includedTaxPrice || 0) * (inCount || 0)).toFixed(3);
            this.price = includedTaxPrice;
            d.money = t;
        },
        // 查询包号数据
        searchBaleNum(d, index) {
            let { woodSalesDeliveryGoodsList } = this.form;
            let { pieceCount, baleNum } = d;

            if (baleNum == null || baleNum == "") {
                this.$message.error("包号为空");
                this.reset();
            } else {
                this.queryParams.baleNum = baleNum;
                this.$Api.storage.report
                    .inventory(this.queryParams)
                    .then((res) => {
                        if (res.rows.length == 0) {
                            this.$message.error("不存在此包号，请重新输入");
                        } else {
                            res.rows.forEach((v) => {
                                woodSalesDeliveryGoodsList =
                                    woodSalesDeliveryGoodsList.splice(
                                        index,
                                        1,
                                        v
                                    );
                            });
                        }
                    })
                    .catch(() => {});
            }
        },
        // 获取详情
        getSalesDelivery() {
            let { deliveryId } = this;
            this.$Api.sales.delivery.inDetail(deliveryId).then((res) => {
                let { data, code } = res;
                if (code === 200) {
                    data.woodSalesDeliveryGoodsList =
                        data.woodSalesDeliveryGoodsList;

                    this.form = data;
                    data.woodSalesDeliveryGoodsList.forEach((v) => {
                        this.form.taxRate = Number(v.taxRate);
                        v.inCount = v.count;
                    });
                }
            });
        },
        // 根据salesId获取销售订单详情
        getSalesOrderDetailList(salesId) {
            if (this.loading) {
                return false;
            }
            this.loading = true;
            return this.$Api.sales.order
                .detail(salesId)
                .then((res) => {
                    let { data, code } = res;
                    if (code == 200) {
                        data.woodSalesDeliveryGoodsList =
                            data.woodSalesOrderGoodsList;
                        delete data.woodSalesOrderGoodsList;
                        data.auditStatus = 0;
                        this.form = data;
                        data.woodSalesDeliveryGoodsList.forEach((v) => {
                            this.form.taxRate = Number(v.taxRate);
                            v.oneCount = Number(v.count) / Number(v.pieceCount);
                            v.inCount = v.count;
                        });
                        this.loading = false;
                    }
                })
                .catch(() => {
                    this.loading = false;
                });
        },
        //查询订单详情
        searchInputChange(salesId) {
            this.getSalesOrderDetailList(salesId).then(()=>{
                this.getReceiptCode();
            });
        },

        // 取消按钮
        cancel() {
            this.$refs["form"].validate((valid) => {
                if (valid) {
                    this.dialogTable = false;
                    this.open = false;
                }
            });
        },
        // 表格重置
        reset() {
            this.form.woodSalesDeliveryGoodsList = [
                {
                    baleNum: null, // 包号
                    goodsName: null, // 品名
                    brandName: null, // 品牌
                    level: null, //等级
                    warehouse: null, // 仓库
                    ply: null, // 厚度
                    width: null, // 宽度
                    length: null, // 长度
                    sliceCount: null, // 片数
                    pieceCount: null, // 件数
                    count: null, // 方数
                    oneCount: null, //单包方数
                    includedTaxPrice: null, // 单价
                    money: null, // 金额
                    goodsStatus: null, // 货物状态
                    pactName: null, //开证公司
                    remark: null, // 备注
                },
            ];
        },

        /** 修改按钮操作 */
        handleUpdate(row) {
            this.formData = row;
            this.open = true;
            this.title = "修改信息";
        },
        /** 保存提交按钮  方数对比*/
        submitForm() {

            let { taxRate, woodSalesDeliveryGoodsList } = this.form;
            woodSalesDeliveryGoodsList.forEach((item) => {
                item.taxRate = taxRate;
                this.price = item.includedTaxPrice;
                item.gcountId;
                item.count = item.inCount;
                item.inWarehouseTime = item.inTime;

            });
   
            this.$refs["form"].validate((pass, error) => {
                pass &&
                    this.$refs["TableForm"].checkForm(
                        (TableFormPass, error) => {
                            if (TableFormPass) {
                                if (this.price != undefined || this.price != null) {
                                    this.$Api.sales.delivery.add(this.form).then((res) => {
                                        if (res.code == 200) {
                                            this.deliveryId = res.data;
                                            this.msgSuccess("操作成功");
                                            const id = this.deliveryId;
                                            let path = `/sales/salesDelivery/list/${id}`;
                                            this.$router.push({
                                                path,
                                            });
                                        } else {
                                            this.$message.error("操作失败");
                                        }
                                    });
                                } else {
                                    this.$message.error("请输入含税单价");
                                }
                            }
                        }
                    );
            });
        },
        //保存并新增
        saveHandleAdd() {
            this.submitForm();
            this.reset();
            this.form.deliveryId = null;
        },
        // 新增
        newAddSell() {
            this.$router.push({ path: "/sale/receipts/outbound" });
            this.reset();
        },
        // 审核与反审核 审核状态;0未审核 1已审核
        setAuditStatus() {
            let { deliveryId } = this;
            let { auditStatus } = this.form;

            this.$confirm(
                "是否确认" +
                    `${auditStatus == 0 ? "审核" : "反审核"}` +
                    '采购订单信息编号为"' +
                    deliveryId +
                    '"的数据项?',
                "警告",
                {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning",
                }
            )
                .then(() => {
                    let nextAudit = auditStatus == 1 ? 0 : 1;
                     this.$Api.sales.delivery.checkStatus({
                            ids: [deliveryId],
                            auditStatus:nextAudit
                        })
                        .then((res) => {
                            if (res.code == 200) {
                                this.getSalesDelivery();
                                this.msgSuccess( `${auditStatus == "1" ? '反审核' : '审核'}`+"成功");
                            } else {
                                this.$message.error("操作失败");
                            }
                        })
                        .catch(() => {});
                })
                .catch(() => {});
        },
        // 收款按钮操作
        purchasingSystem() {
            const orderId = this.form.orderId;
            let path = `/purchase/invoice/putInstorage?orderId=${orderId}`;
            this.$router.push({
                path,
            });
        },
    },
};
</script>

<style lang="scss" scoped>
::v-deep.page-wood-sales-note {
    .img-audit {
        position: absolute;
        right: 30px;
        bottom: 30px;
        transform: rotate(-18deg);
        pointer-events: none;
    }

    .sumbit-btn-group {
        margin: 0 0 20px 0;
        display: flex;
        align-items: center;
        justify-content: flex-end;
        .empty {
            width: 100%;
            flex: 1;
        }
    }
    .btn-group {
        display: flex;
        align-items: center;
        justify-content: space-evenly;
    }

    .disabled {
        color: #a8a8a8;
    }

    .error {
        color: #fa3e3e;
    }

    .form-remark {
        display: grid;
        margin: 20px 15px 15px;
        .el-form-item__contentt {
            display: inline-block;
            width: 100%;
        }
    }
}
</style>
